<template>
  <div class="login-container flx-center">
    <div class="login-box">
      <SwitchDark class="dark" />
      <div class="login-form">
        <div class="login-logo">
          <img class="login-icon" src="@/assets/images/logo.png" alt="" />
          <h2 class="logo-text">好房挑ERP系统</h2>
        </div>
        <phoneForm @valid="valid">
          <template #default>
            <!-- <wxForm @wx-login="wxLogin"></wxForm> -->
          </template>
        </phoneForm>
      </div>
    </div>
    <VCode :show="codeShow" @close="onClose" @success="onSuccess"></VCode>
    <siteChoose ref="siteRef" @login="loginWidthSite"></siteChoose>
  </div>
</template>

<script setup lang="ts" name="login">
import SwitchDark from "@/components/SwitchDark/index.vue";
import { ref } from "vue";
import phoneForm from "./components/phoneForm.vue";
import VCode from "vue3-puzzle-vcode";
import { useRouter } from "vue-router";
import { getTimeState } from "@/utils";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { useLoginStore } from "@/stores/modules/login";
import siteChoose from "./components/siteChoose.vue";
import { getSiteManageList, loginSiteIn } from "@/api/modules/region";
// import wxForm from "./components/wxForm.vue";

const siteRef = ref<InstanceType<typeof siteChoose> | null>();

const { type } = useLoginStore();

const loading = ref(false);

const nowLoginForm = ref();

const valid = (val: any) => {
  codeShow.value = true;
  nowLoginForm.value = val;
};

// 判断是否为站点登录
const siteLogin = async (list: any[]) => {
  if (list.length > 1) {
    siteRef.value?.open(list);
  } else if (list.length === 1) {
    try {
      await loginWidthSite(list[0].id);
    } catch (error) {}
  }
};

// 站点登录
const loginWidthSite = async (id: any) => {
  try {
    await loginSiteIn(id);
    siteRef.value?.close();
    nextApi();
    loading.value = false;
  } catch (error) {}
};

const onSuccess = async () => {
  loading.value = true;
  try {
    // 1.执行登录接口
    const { data } = await loginApi(type, { ...nowLoginForm.value });
    userStore.setToken(data.access_token);
    const { data: list } = await getSiteManageList();
    switch (type) {
      case "admin":
        break;
      case "site":
        siteLogin(list as any);
        codeShow.value = false;
        return;
      case "nor":
        break;
      default:
        break;
    }
    nextApi();
  } finally {
    loading.value = false;
  }
};

const nextApi = async () => {
  // 清除登录计时
  sessionStorage.removeItem("login_session");
  // 2.添加动态路由
  await Promise.all([initDynamicRouter(), userStore.setUserInfo()]);

  // 3.清空 tabs、keepAlive 数据
  tabsStore.closeMultipleTab();
  keepAliveStore.setKeepAliveName();

  // 4.跳转到首页
  router.push({ name: "home" });
  ElNotification({
    title: getTimeState(),
    message: "欢迎登录 好房挑管家系统",
    type: "success",
    duration: 3000
  });
};

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const onClose = () => {
  codeShow.value = false;
};
const codeShow = ref(false);

// 微信登录
// const wxLogin = () => {
//   const redirect_uri = encodeURIComponent("https://jsmk.haofangtiao.cn/login");
//   const appId = "wx9b451009f06faf0b";
//   const wxUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_login&state=${generateRandom6DigitNumber()}#wechat_redirect`;
//   window.location.href = wxUrl;
// };
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
